#!/usr/bin/env python
'''
Functions that handles the breweries
'''

import gobject
import gtk
import Gui

import Brands

from DB import *
from GladeWidgets import GladeWidget

class Brewery:
    NAME        = 0
    OWNED_BY    = 1
    COUNTRY     = 2
    STATE       = 3
    CITY        = 4
    COASTERS    = 5

def on_btnAddBrewery_clicked(wnd, event):
    '''Add a new brewery'''
    wndBreweryAdd = GladeWidget("wndAddBrewery")
    Gui.setComboboxCountries(wndBreweryAdd["comboCountry"])

    res = False
    while (res == False):
        ret = wndBreweryAdd["wndAddBrewery"].run()
        if (ret == 1): # cancel
            res = True
        elif (ret == 2): # add
            res = _addBrewery(wndBreweryAdd)
            if (res == True):
                showTreeview(wnd["treeviewBreweries"])
    wndBreweryAdd["wndAddBrewery"].destroy()

def on_btnEditBrewery_clicked(wnd, event):
    '''Edit a new brewery'''
    wndBreweryEdit = GladeWidget("wndEditBrewery")

    if (_setupEditWindow(wnd, wndBreweryEdit) == False):
        return False

    # get the old name (used to perform the update)
    model, iterator = wnd["treeviewBreweries"].get_selection().get_selected()
    oldname = model.get_value(iterator, Brewery.NAME)

    res = False
    while (res == False):
        ret = wndBreweryEdit["wndEditBrewery"].run()
        if (ret == 1): # cancel
            res = True
        elif (ret == 2): # apply
            res = _editBrewery(wndBreweryEdit, oldname)
            if (res == True):
                showTreeview(wnd["treeviewBreweries"])
                Brands.showTreeview(wnd["treeviewBrands"])
    wndBreweryEdit["wndEditBrewery"].destroy()

def on_btnDelBrewery_clicked(wnd, event):
    '''Delete a brewery'''
    model, iterator = wnd["treeviewBreweries"].get_selection().get_selected()
    if not iterator:
        Gui.ErrorBox(str="Select an item to delete first!")
    else:
        yesno = gtk.MessageDialog(wnd["wndMain"], gtk.DIALOG_MODAL, gtk.MESSAGE_QUESTION, gtk.BUTTONS_YES_NO,
                "WARNING: deleting this brewery will also delete all the brands and coasters" +
                " that are associated with it. Do you still want to delete it?")

        def delBreweryResponse(window, response_id):
            if response_id == gtk.RESPONSE_YES:
                path = wnd["treeviewBreweries"].get_model().get_path(iterator)[Brewery.NAME]
                db = DB()
                db.deleteBrewery(model.get_value(iterator, Brewery.NAME))
                wnd["treeviewBreweries"].get_model().remove(iterator)
                Brands.showTreeview(wnd["treeviewBrands"])
                # TODO: show coasters again
            yesno.destroy()

        yesno.connect("response", delBreweryResponse)
        yesno.show()


def setTreeModel(wnd):
    '''Set the treemodel for the treeview on the mainwindow'''
    treeview = wnd["treeviewBreweries"]
    model = gtk.ListStore(  gobject.TYPE_STRING,    # name
                            gobject.TYPE_STRING,    # owned by
                            gobject.TYPE_STRING,    # country
                            gobject.TYPE_STRING,    # state/region
                            gobject.TYPE_STRING,    # city
                            gobject.TYPE_INT)       # coasters num
    treeview.set_model(model)
    treeview.set_headers_clickable(True)

    Gui.treeviewAddGeneralTextColumn(treeview, "Brewery", Brewery.NAME, resizable=True, reorderable=True)
    Gui.treeviewAddGeneralTextColumn(treeview, "Owned by", Brewery.OWNED_BY, resizable=True, reorderable=True)
    Gui.treeviewAddGeneralTextColumn(treeview, "Country", Brewery.COUNTRY, resizable=True, reorderable=True)
    Gui.treeviewAddGeneralTextColumn(treeview, "State/Region", Brewery.STATE, resizable=True, reorderable=True)
    Gui.treeviewAddGeneralTextColumn(treeview, "City", Brewery.CITY, resizable=True, reorderable=True)
    Gui.treeviewAddGeneralTextColumn(treeview, "Coasters", Brewery.COASTERS, resizable=True, reorderable=True)

def showTreeview(treeview, filter='%'):
    '''Fill the treeview with brands informations (you can pass
    "filter=<sqlwildcard>" in order to show just some infos'''
    db = DB()
    breweries = db.getAllBreweriesInfo(filter)
    treeview.get_model().clear()
    
    for name, owned_by, country, state, city in breweries:
        _addTreeviewRow(treeview,
                        name,
                        owned_by,
                        country,
                        state,
                        city,
                        db.getCoastersNumByBrewery(name))

def _addTreeviewRow(treeview, name, owned_by=None, country=None, state=None, city=None, coasters=0):
    '''Add a new row to the treeview'''
    model = treeview.get_model()
    item = model.append(None)
    model.set_value(item, Brewery.NAME, name)
    model.set_value(item, Brewery.OWNED_BY, owned_by)
    model.set_value(item, Brewery.COUNTRY, country)
    model.set_value(item, Brewery.STATE, state)
    model.set_value(item, Brewery.CITY, city)
    model.set_value(item, Brewery.COASTERS, coasters)

def _setupEditWindow(wndMain, wndEdit):
    model, iterator = wndMain["treeviewBreweries"].get_selection().get_selected()
    if (not iterator):
        Gui.ErrorBox(str="Select an item to edit first!")
        return False

    name = model.get_value(iterator, Brewery.NAME)
    owner = model.get_value(iterator, Brewery.OWNED_BY)
    country = model.get_value(iterator, Brewery.COUNTRY)
    state = model.get_value(iterator, Brewery.STATE)
    city = model.get_value(iterator, Brewery.CITY)

    if (owner == None):
        owner = ""
    if (state == None):
        state = ""
    if (city == None):
        city = ""

    wndEdit["txtName"].set_text(name)
    wndEdit["txtOwner"].set_text(owner)
    wndEdit["txtState"].set_text(state)
    wndEdit["txtCity"].set_text(city)
    Gui.setComboboxCountries(wndEdit["comboCountry"], active=country)

    return True

def _addBrewery(wnd):
    '''A wrapper to the database function that adds a new brewery'''
    name = wnd["txtName"].get_text()
    owner = wnd["txtOwner"].get_text()
    country = wnd["comboCountry"].get_active_text()
    state = wnd["txtState"].get_text()
    city = wnd["txtCity"].get_text()

    if ((name == None) or (len(name) == 0)):
        Gui.ErrorBox(str="Please insert all the required fields (a brewery name is required)")
        return False

    if (len(owner) == 0):
        owner = None
    if (len(country) == 0):
        country = None
    if (len(state) == 0):
        state = None
    if (len(city) == 0):
        city = None

    db = DB()
    try:
        db.addBrewery(name, owner, country, state, city)
        return True
    except ExistingError:
        Gui.ErrorBox(str="A brewery with this name is already existing")
        return False

def _editBrewery(wnd, oldname):
    '''A wrapper to the database function that edit a brewery'''
    name = wnd["txtName"].get_text()
    owner = wnd["txtOwner"].get_text()
    country = wnd["comboCountry"].get_active_text()
    state = wnd["txtState"].get_text()
    city = wnd["txtCity"].get_text()

    if ((name == None) or (len(name) == 0)):
        Gui.ErrorBox(str="Please insert all the required fields (a brewery name is required)")
        return False

    if (len(owner) == 0):
        owner = None
    if (len(country) == 0):
        country = None
    if (len(state) == 0):
        state = None
    if (len(city) == 0):
        city = None

    db = DB()
    try:
        db.updateBrewery(oldname, name, owner, country, state, city)
        return True
    except ExistingError:
        Gui.ErrorBox(str="A brewery with this name is already existing")
        return False
